package org.carshared.sqlite;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import org.carshared.utils.TravelBeen;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class DBAdapterTravel {

	// Campos de la BD
	public static final String COLUMN_ID = "id";
	public static final String COLUMN_ORIGENDESTINO = "origenDestino";
	public static final String COLUMN_PRECIOCOMBUSTIBLE = "precioCombustible";
	public static final String COLUMN_RECORRIDO = "recorrido";
	public static final String COLUMN_KMTRAYECTO = "kmTrayecto";
	public static final String COLUMN_GASTOCOCHE = "gastoCoche";
	public static final String COLUMN_ACUMULADO = "acumulado";
	public static final String COLUMN_PRECIOTRAYECTO = "precioTrayecto";
	public static final String COLUMN_FECHA = "fecha";
	public static final String COLUMN_NPASAJEROS = "nPasajeros";
	public static final String COLUMN_TIPO = "tipo";

	private static final String DATABASE_TABLE_TRAVEL = "Travel";
	private Context context;
	private SQLiteDatabase database;
	private MySQLiteHelper dbHelper;

	public DBAdapterTravel(Context context) {
		this.context = context;
	}

	public DBAdapterTravel open() throws SQLException {
		dbHelper = new MySQLiteHelper(context);
		database = dbHelper.getWritableDatabase();
		return this;
	}

	public void close() {
		dbHelper.close();
	}

	/**
	 * Crea una nueva tarea, si esto va bien retorna la rowId de la tarea, de lo
	 * contrario retorna -1
	 */
	public long createTravel(TravelBeen travel) {
		open();
		ContentValues initialValues = createContentValues(travel);

		long vControl = database.insert(DATABASE_TABLE_TRAVEL, null,
				initialValues);
		dbHelper.close();
		return vControl;
	}

	// Actualiza la tarea
	public int update(TravelBeen travel) {
		ContentValues updateValues = createContentValues(travel);
		open();
		int i = database.update(DATABASE_TABLE_TRAVEL, updateValues,
				COLUMN_ORIGENDESTINO + "=" + "'" + travel.getOrigenDestino()
						+ "'", null);
		dbHelper.close();
		return i;
	}

	// Borra la tarea
	public void deleteTravel(String rowId) {
		open();
		database.delete(DATABASE_TABLE_TRAVEL, COLUMN_ORIGENDESTINO + "=" + "'"
				+ rowId + "'", null);
		dbHelper.close();
	}

	// Returna un Cursor que contiene todos los items
	public ArrayList<TravelBeen> fetchAllTravel(String tipo) {
		open();
		Cursor mCursor = database.query(DATABASE_TABLE_TRAVEL, new String[] {
				COLUMN_ID, COLUMN_ORIGENDESTINO, COLUMN_PRECIOCOMBUSTIBLE,
				COLUMN_RECORRIDO, COLUMN_KMTRAYECTO, COLUMN_GASTOCOCHE,
				COLUMN_ACUMULADO, COLUMN_PRECIOTRAYECTO, COLUMN_FECHA,
				COLUMN_NPASAJEROS, COLUMN_TIPO }, COLUMN_TIPO + "=" + "'"
				+ tipo + "'", null, null, null, null);

		return cursorToArrayList(mCursor);
	}

	// Returna un Cursor que contiene la info del item
	public TravelBeen fetchTravel(String idTravel) throws SQLException {
		open();

		Cursor mCursor = database.query(true, DATABASE_TABLE_TRAVEL,
				new String[] { COLUMN_ID, COLUMN_ORIGENDESTINO,
						COLUMN_PRECIOCOMBUSTIBLE, COLUMN_RECORRIDO,
						COLUMN_KMTRAYECTO, COLUMN_GASTOCOCHE, COLUMN_ACUMULADO,
						COLUMN_PRECIOTRAYECTO, COLUMN_FECHA, COLUMN_NPASAJEROS,
						COLUMN_TIPO }, COLUMN_ORIGENDESTINO + "=" + "'"
						+ idTravel, null, null, null, null, null);
		if (mCursor != null) {
			mCursor.moveToFirst();
		}
		ArrayList<TravelBeen> result = cursorToArrayList(mCursor);
		return result.get(0);
	}

	private ArrayList<TravelBeen> cursorToArrayList(Cursor c) {

		ArrayList<TravelBeen> result = new ArrayList<TravelBeen>();
		Calendar cal = Calendar.getInstance();

		while (c.moveToNext()) {
			try {

				Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(c
						.getString(7));
				cal.setTime(date);
			} catch (Exception e) {
				cal = null;
			}
			TravelBeen t = new TravelBeen(c.getInt(0), c.getString(1),
					c.getFloat(2), c.getString(3), c.getInt(4), c.getFloat(5),
					c.getFloat(6), c.getFloat(7), cal, c.getInt(9),
					c.getString(10));
			result.add(t);
		}

		dbHelper.close();
		return result;
	}

	private ContentValues createContentValues(TravelBeen travel) {
		ContentValues values = new ContentValues();
		values.put(COLUMN_ORIGENDESTINO, travel.getOrigenDestino());
		values.put(COLUMN_PRECIOCOMBUSTIBLE, travel.getPrecioCombustible());
		values.put(COLUMN_RECORRIDO, travel.getRecorrido());
		values.put(COLUMN_KMTRAYECTO, travel.getKmTrayecto());
		values.put(COLUMN_GASTOCOCHE, travel.getGastoCoche());
		values.put(COLUMN_NPASAJEROS, travel.getnPasajeros());
		values.put(COLUMN_ACUMULADO, travel.getAcumulado());
		values.put(COLUMN_PRECIOTRAYECTO, travel.getPrecioTrayecto());
		values.put(COLUMN_TIPO, travel.getTipo());
		if (travel.getFecha() != null) {
			values.put(COLUMN_FECHA, travel.getFecha().toString());
		} else {
			values.put(COLUMN_FECHA, "");
		}

		return values;
	}
}